<?php
/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/10
 * Time: 16:01
 */

namespace app\api\controller;


use app\api\BaseController;
use app\common\model\InquiryModel;
use app\common\model\Inviter;
use app\common\model\Search;
use app\common\model\Storeplate;
use app\common\model\Transport;
use app\home\controller\Sellerinquiry;
use app\service\GoodsService;
use app\common\model\Goodproject;
use app\common\model\Goodsclass;
use app\common\model\Brand;
use app\common\model\Pxianshigoods;
use app\common\model\Refundreturn;
use think\Db;
use think\Request;
use PHPExcel;
use PHPExcel_IOFactory;

/**
 * @title 商品询价
 * @description 商品询价相关接口
 */
class Goodinquiry extends BaseController
{
    const PAGESIZE = 150;

    /**
     * GET请求
     * 获取店铺类型和工位。返回格式
     * {
     * code: 200,
     * msg: 'success',
     * data: [
     * {
     * id:1,
     * inquiry_name:'店铺名称',
     * inquiry_station: {
     * station_id: 1,
     * station_name: '工位名称'
     * }
     * }]
     * }
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getStoreTypeAndStation()
    {
        // 获取所有商铺
        $inquires = Db::table('ds_inquiries')->where('is_del', '=', 0)->select();

        $data = [];
        foreach ($inquires as $key => $value) {
            $data[$key] = [
                'id' => $value['id'],
                'inquiry_name' => $value['inquiry_name'],
            ];
            $where = [
                'status' => 1,
                'inquiry_id' => $value['id']
            ];
            $inquires_station = Db::table('ds_inquiry_station')->where($where)->select();
            foreach ($inquires_station as $k => $v) {
                $data[$key]['inquiry_station'][$k] = [
                    'station_id' => $v['station_id'],
                    'station_name' => $v['station_name']
                ];
            }
        }

        json_success_return($data);
    }

    /**
     * post请求
     * 根据店铺id，工位id，工位数量，配置方法取出相关商品
     * @param Request $request
     *  $inquiry_id    int   店铺id
     *  $station       array 工位id和数量，格式[工位id=>数量]
     *  $config        int   配置 1低配，2中配，3高配
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function makeGoods(Request $request)
    {
        $inquiry_id = $request->post('inquiry_id', 0); // 店铺id
        $station = $request->post('station'); // 工位信息数组[工位id=>数量]
        $config = $request->post('config', 0); // 配置，中高低配置

        #转义
        $station = json_decode(htmlspecialchars_decode($station), true);

        // 处理工位数量
        $arr2 = [];
        foreach ($station as $key => $val) {
            if (empty($val)) { // 去除工位上为0的数据
                unset($station[$key]);
            }
            $arr2[] = $val['id'];
        }
        $station_id = implode(',', $arr2);

        // 根据店铺id，工位，和配置查询相关商品
        $goods = Db::table('ds_inquiry_info')
            ->where('inquiry_id', '=', $inquiry_id)
            ->where('station_id', 'in', $station_id)
            ->where('is_del', '=', 0)
            ->where('status', '=', 0)
            ->select();

        $data = [];
        foreach ($goods as $key => $val) {
            // 去除没有改配置的商品  (如果需要询价的配置不在里面，直接跳出)
            $config_arr = explode(',', $val['good_config']);
            if (!in_array($config, $config_arr)) {
                unset($goods[$key]);
                continue;
            }
            // 根据工位数量计算返回商品的数量。工位数量*商品数量
            // $val['sum_num'] = 0;

            // if (empty($val['num'])) {
            //     $num = 1;
            // } else {
            //     $num = $val['num'];
            // }
            // $val['sum_num'] = $num*$station[$val['station_id']];
            $goods_detail = db('goodscommon')->alias('g')
                ->join('brand b', 'b.brand_id = g.brand_id')
                ->where(['goods_commonid' => $val['goods_id']])
                ->field('g.*,b.brand_name')
                ->find();

            $config = db('config')->where('code', 'qiniu_http')->find();

            $goods_info = [
                'goods_id' => $val['goods_id'],
                'goods_name' => $goods_detail['goods_name'],
                'goods_image' => $config['value'] . '/' . $goods_detail['goods_image'],
                'brand_name' => $goods_detail['brand_name'],
                'goods_price' => $goods_detail['goods_price'],
                'spec_values' => '',
                'num' => $val['num'],
            ];
            $data[] = $goods_info;
        }
        json_success_return($data);
    }

    #询价搜索商品
    public function getGoodsList(\app\common\model\Goods $goods_model)
    {
        $keyword = input('param.keyword'); #关键词
        $salenum_sort = intval(input('param.salenum_sort')); #销量排序 1升序 2降序
        $is_price = input('is_price_sort', ''); #价格排序 1升序 2降序

        $class_id = intval(input('param.class_id'));  #分类id
        $brand_id = intval(input('param.brand_id'));  #品牌id

        #默认情况
        $order = 'goods.goods_salenum desc'; #销量降序

        $filed = '*';
        $condition = array();
        $store_id = get_parent_store_id();
        $condition['y_goods.store_id'] = $store_id;

        if ($brand_id > 0) {
            $condition['goods.brand_id'] = $brand_id;
        }
        if ($class_id > 0) {
            $condition['goods.gc_id_3'] = $class_id;
        }

        if ($keyword != '') {
            $condition['goods.goods_name'] = array('like', '%' . $keyword . '%');
        }

        $goods_list = $goods_model->getGoodsUnionList($condition, $filed, $order, 'goods.goods_id', self::PAGESIZE);

        $supplier_type = get_supplier_type();

        $config = db('config')->where('code', 'qiniu_http')->find();

        $new_goods_list = [];
        if ($supplier_type == 1) {
            #加价
            foreach ($goods_list as $k => $v) {
                $y_goods_info = db('y_goods')->where('store_id', $store_id)->where('goods_id', $v['goods_id'])->find();
                //p($y_goods_info);die;
                $new_goods_list[$k]['goods_id'] = $v['goods_id'];
                $new_goods_list[$k]['goods_name'] = $v['goods_name'];
                $new_goods_list[$k]['brand_name'] = $v['brand_name'];
                $new_goods_list[$k]['final_price'] = (float)$goods_list[$k]['gu_final_price'] + (float)$y_goods_info['price'];
                $new_goods_list[$k]['goods_salenum'] = $v['goods_salenum'];
                $new_goods_list[$k]['spec_values'] = $v['spec_values'];
                $new_goods_list[$k]['goods_image'] = $config['value'] . '/' . $v['goods_image'];
            }
        } else {
            #按照提成走
            foreach ($goods_list as $k => $v) {
                $new_goods_list[$k]['goods_id'] = $v['goods_id'];
                $new_goods_list[$k]['goods_name'] = $v['goods_name'];
                $new_goods_list[$k]['brand_name'] = $v['brand_name'];
                $new_goods_list[$k]['final_price'] = $goods_list[$k]['ti_final_price'];
                $new_goods_list[$k]['goods_salenum'] = $v['goods_salenum'];
                $new_goods_list[$k]['spec_values'] = $v['spec_values'];
                $new_goods_list[$k]['goods_image'] = $config['value'] . '/' . $v['goods_image'];
            }
        }
        #价格排序
        if (!empty($is_price)) {
            #1:升序 2：降序
            $last_names = array_column($new_goods_list, 'final_price');
            if ($is_price == 1) {
                array_multisort($last_names, SORT_ASC, $new_goods_list);
            } else {
                array_multisort($last_names, SORT_DESC, $new_goods_list);
            }
        }
        #销量排序
        if (!empty($salenum_sort)) {
            #1:升序 2：降序
            $last_names = array_column($new_goods_list, 'goods_salenum');
            if ($salenum_sort == 1) {
                array_multisort($last_names, SORT_ASC, $new_goods_list);
            } else {
                array_multisort($last_names, SORT_DESC, $new_goods_list);
            }
        }

        json_success_return($new_goods_list);
    }

    /**
     * post提交
     * 保存询价方案列表
     * 参数：
     *  $goods_list     array       商品列表，格式[商品id=>数量]
     *  $member_id      int         用户id
     *  $scheme_name    string      方案名称
     *  $inquiry_id     int         店铺类型id
     * @param Request $request
     */
    public function saveGoodsList(Request $request)
    {
        $goods_list = $request->post('goods'); // 商品，格式[商品id=>数量]
        $member_id = $this->user_id;
        $scheme_name = $request->post('scheme_name', ''); // 方案名称
        $inquiry_id = $request->post('inquiry_id', ''); // 店铺类型id
        $id = $request->post('id', ''); // 店铺类型id

        if (empty($member_id) || empty($goods_list)) return json_fail_return('参数错误');

        #转义
        $goods_list = json_decode(htmlspecialchars_decode($goods_list), true);

        $arr1 = [];//获取数量
        $arr2 = [];//获取商品id
        foreach ($goods_list as $key => $val) {
            if (empty($val)) {
                unset($goods_list[$key]);
            }
            $arr1[] = $val['num'];
            $arr2[] = $val['id'];
        }

        if (empty($member_id)) {
            return json_fail_return('参数错误');
        }
        if (empty($scheme_name)) {
            return json_fail_return('缺少方案名称');
        }


        $data = [
            'scheme_name' => $scheme_name,
            'inquiry_id' => $inquiry_id,
            'member_id' => $member_id,
            'goods_id' => implode(',', $arr2),
            'num' => implode(',', $arr1),
            'c_time' => time(),
        ];
        if ($id) {
            $res = Db::table('ds_seller_inquiry')->where('id', $id)->data($data)->update();
            if ($res) {
                return json_success_return(['id' => $id], '操作成功');
            }
            return json_fail_return('保存失败');
        } else {
            $id = Db::table('ds_seller_inquiry')->insertGetId($data);
            if ($id) {
                return json_success_return(['id' => $id], '操作成功');
            }
            return json_fail_return('保存失败');
        }




    }


    /**
     * Notes:获取询价方案的详情
     * User: shen
     * Date: 2020/4/28
     * Time: 9:15
     */
    public function getGoodsInfo(Request $request)
    {
        $id = $request->post('id', ''); // id
        if (empty($id)) {
            return json_fail_return('缺少方案id');
        }
        $info = Db::table('ds_seller_inquiry')->where('id', $id)->find();
        if (empty($info)) {
            return json_fail_return('信息错误');
        }
        if ($info['goods_id'] && $info['num'] ) {

            $goods_list = db('goods')->alias('g')
                ->join('brand b', 'g.brand_id = b.brand_id')
                ->where('g.goods_id', 'in', $info['goods_id'])
                ->select();
            $supplier_type = get_supplier_type();
            $store_id = get_parent_store_id();
            $config = db('config')->where('code', 'qiniu_http')->find();
              $nums_array = explode(',',$info['num']);
            if ($supplier_type == 1) {
                #加价
                foreach ($goods_list as $k => $v) {
                    $y_goods_info = db('y_goods')->where('store_id', $store_id)->where('goods_id', $v['goods_id'])->find();
                    $goods_info[$k]['goods_id'] = $v['goods_id'];
                    $goods_info[$k]['goods_name'] = $v['goods_name'];
                    $goods_info[$k]['brand_name'] = $v['brand_name'];
                    $goods_info[$k]['final_price'] = (float)$goods_list[$k]['gu_final_price'] + (float)$y_goods_info['price'];
                    $goods_info[$k]['goods_salenum'] = $nums_array[$k];
                    $goods_info[$k]['spec_values'] = $v['spec_values'];
                    $goods_info[$k]['goods_image'] = $config['value'] . '/' . $v['goods_image'];
                }
            } else {
                #按照提成走
                foreach ($goods_list as $k => $v) {
                    $goods_info[$k]['goods_id'] = $v['goods_id'];
                    $goods_info[$k]['goods_name'] = $v['goods_name'];
                    $goods_info[$k]['brand_name'] = $v['brand_name'];
                    $goods_info[$k]['final_price'] = $goods_list[$k]['ti_final_price'];
                    $goods_info[$k]['goods_salenum'] = $nums_array[$k];
                    $goods_info[$k]['spec_values'] = $v['spec_values'];
                    $goods_info[$k]['goods_image'] = $config['value'] . '/' . $v['goods_image'];
                }
            }

        } else {
            $goods_info = array();

        }

        $return_data = [
            'info' => $info,
            'goods_info' => $goods_info
        ];

        json_success_return($return_data, '获取成功');
    }


    /**
     * Get请求
     * 根据用户id获取询价方案列表
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMyInquiryList(Request $request)
    {
        $member_id = $this->user_id;
        if (empty($member_id)) return json_fail_return('参数错误');

        $data = Db::table('ds_seller_inquiry')->where('member_id', '=', $member_id)->where('is_del', '=', 0)->order('c_time desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['c_time'] = date('Y-m-d H:i:s', $v['c_time']);
            $goods_array = explode(',', $v['goods_id']);
            $data[$k]['count'] = count($goods_array);
        }
        return json_success_return($data);
    }

    /**
     * Post请求
     * 根据用id和方案id删除该方案
     * member_id    int     用户id
     * id           int     方案id
     *
     * @param Request $request
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delMyInquiry(Request $request)
    {
        $member_id = $this->user_id; // 用户id
        $id = $request->post('id', 0);  // 询价列表id
        if (empty($member_id) || empty($id)) return json_fail_return('参数错误');

        $res = Db::table('ds_seller_inquiry')
            ->where('member_id', '=', $member_id)
            ->where('id', '=', $id)
            ->where('is_del', '=', 0)
            ->update(['is_del' => 1, 'del_time' => time()]);

        if ($res) {
            return json_success_return([],'方案已删除');
        }
        return json_fail_return([],'删除失败');
    }

    /**
     * post请求
     * 批量加入购物车方法
     * 参数
     *  member_id   int     用户id
     *  $goods      array   商品，格式[商品id=>数量]
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addShopCar(Request $request)
    {
        $buyer_id = $this->user_id; // 用户id
        $goods = $request->post('goods'); // 商品，格式[商品id=>数量]

        if (empty($buyer_id) || empty($goods)) return json_fail_return('参数错误');

        #转义
        $goods = json_decode(htmlspecialchars_decode($goods), true);

        $arr1 = [];//获取数量
        $arr2 = [];//获取商品id
        foreach ($goods as $key => $val) {
            if (empty($val)) { // 去除工位上为0的数据
                unset($goods[$key]);
            }
            $arr1[] = $val['num'];
            $arr2[] = $val['id'];
        }

        $good_ids = implode(',', $arr2);
        #判断商品是否有重复的
        // 查询商品
        // $good_ids = array_keys($goods);
        $goods_arr = Db::table('ds_goods')->where('goods_id', 'in', $good_ids)
            ->select();
        $goods_arr = \app\common\model\Goods::all(function ($query) use ($good_ids) {
            $query->where('goods_id', 'in', $good_ids);
        });

        // 初始化购物车商品信息
        $data = [];
        foreach ($goods_arr as $key => $val) {
            $data[] = [
                'buyer_id' => $buyer_id,
                'store_id' => $val->store_id,
                'store_name' => $val->store_name,
                'goods_id' => $val->goods_id,
                'goods_name' => $val->goods_name,
                'goods_price' => $val->goods_price,
                'goods_num' => $arr1[$key],
                'goods_image' => $val->goods_image,
                'goods_commonid' => $val->goods_commonid,
            ];
        }

        $res = Db::table('ds_cart')->insertAll($data);
        if ($res) {
            return json_success_return('已成功加入购物车');
        }

        return json_fail_return('添加失败');
    }

    /**
     * post请求
     * 生成询价excel 并导出
     * @param Request $request
     * 参数  邹建伟测试
     *  $inquiry_id    int   店铺id
     *  $station       array 工位id和数量，格式[工位id=>数量]
     *  $config        int   配置 1低配，2中配，3高配
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function export(Request $request)
    {
        $id = $request->post('id', 0); // 店铺id
        $info = Db::table('ds_seller_inquiry')->alias('a')
            ->join('ds_inquiries b', 'a.inquiry_id = b.id')
            ->field('a.*,b.inquiry_name')
            ->where('a.id', $id)->find();
        if (empty($info)) {
            return json_fail_return('信息错误');
        }

        require(EXTEND_PATH . "excel" . DS . 'phpExcel.php');
        $obj = new PHPExcel();
        $excel_data = array();

        if ($info['configure'] == 1) {
            $configure_text = '低端配置';
        } else if ($info['configure'] == 2) {
            $configure_text = '中端配置';
        } else {
            $configure_text = '高端配置';
        }
        $reate_time = date('Y-m-d H:i:s', $info['c_time']);
        $excel_data[0] = array("方案名称：{$info['scheme_name']}", "店铺类型：{$info['inquiry_name']}", "配置类型：{$configure_text}", "创建时间：{$reate_time}", "备注：{$info['remarks']}", '');

        $excel_data[2] = array('序号', '商品名称', '规格', '品牌', '价格(单价)', '数量');
        if ($info['goods_id'] && $info['num']) {

            $goods_list = db('goods')->alias('g')
                ->join('brand b', 'g.brand_id = b.brand_id')
                ->where('g.goods_id', 'in', $info['goods_id'])
                ->select();
            $supplier_type = get_supplier_type();
            $store_id = get_parent_store_id();
            $nums_array = explode(',',$info['num']);
            if ($supplier_type == 1) {
                #加价
                foreach ($goods_list as $k => $v) {
                    $y_goods_info = db('y_goods')->where('store_id', $store_id)->where('goods_id', $v['goods_id'])->find();
                    $goods_info[$k]['goods_name'] = $v['goods_name'];
                    $goods_info[$k]['brand_name'] = $v['brand_name'];
                    $goods_info[$k]['goods_price'] = (float)$goods_list[$k]['gu_final_price'] + (float)$y_goods_info['price'];
                    $goods_info[$k]['num'] = $nums_array[$k];
                    $goods_info[$k]['spec_values'] = $v['spec_values'];
                }
            } else {
                #按照提成走
                foreach ($goods_list as $k => $v) {
                    $goods_info[$k]['goods_name'] = $v['goods_name'];
                    $goods_info[$k]['brand_name'] = $v['brand_name'];
                    $goods_info[$k]['goods_price'] = $goods_list[$k]['ti_final_price'];
                    $goods_info[$k]['num'] =  $nums_array[$k];
                    $goods_info[$k]['spec_values'] = $v['spec_values'];
                }
            }

        }


        foreach ($goods_info as $key => $val) {

            $excel_data[$key + 3] = array($key + 1, $val['goods_name'], $val['spec_values'], $val['brand_name'], $val['goods_price'], $val['num']);
        }
        $objSheet = $obj->getActiveSheet(); //获取当前活跃的sheet的操作对象
        $objSheet->setTitle(date('Y-m-d-H', time()));//给当前的sheet创建名称
        $objSheet->fromArray($excel_data);
        $objWriter = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');//参数写入
        $objWriter->save("./uploads/excel/询价项目.xlsx");//保存
        $files_path = 'http://' . $_SERVER['SERVER_NAME'] . "/uploads/excel/询价项目.xlsx";
        return json_success_return($files_path, '操作成功');

    }


}
